<?php
namespace backend\modules\business\controllers;

use backend\controllers\BaseController;
use yii\helpers\Url;
use common\models\BusRepertory;
use common\models\BusRepertoryInc;
use yii\base\Object;
use yii\data\Pagination;
use common\extended\system\Util;
/**
 * 商品入库管理
 * @author     chenxiaolin
 * @date        2016年2月23日
 * @version     2.0.0
 * @copyright   Copyright 2016 meelier.com
 */
class RepertoryincController extends BaseController{
    public function init()
    {
        parent::init();
        $this->getView()->params['controller_name'] = 'repertory';
    }
    public function actionIndex(){
        $this->redirect(Url::toRoute('repertoryinc/list'));
    }
    /**
     * 商品入库
     * @date: 2016年2月24日 
     * @author: chenxiaolin
     */
    public function actionStorage(){
        //获取session中的临时数据
        $session = \Yii::$app->session;
        if(!$this->request->isPost){
            $type = $this->request->get('type',0);
            $id = $this->request->get('id',0);
            if(!empty($id)){
                if($id < 1){
                    $this->error('参数错误！');
                }
                $str = $this->where;
                $str[] ='repertory_id = :id'; 
                $bind[':id'] = $id;
                $strs = implode(' and ', $str);
                $data = BusRepertory::find()->where($strs,$bind)->one();
                if(empty($data)){
                    $this->error('参数错误！');
                }else{//将新增数据id存入session
                    if(empty($session['repertoryId'])){
                        $session['repertoryId'] = [];
                    }
                    $arr1 = $session['repertoryId'];
                    if(!in_array($id, $arr1)){
                        array_push($arr1,$id);
                    }
                    $session['repertoryId'] = $arr1;
                }
            }
            if(!empty($type) && $type != 1){
                $this->error('参数错误！');
            }
            if($type == 1){
                //清空session
                unset($session['repertoryId']);
                unset($session['repertoryNum']);
            }
            $id = '';
            $repertory = [];
            $count = '';
            $where = $this->where;
            //商品编号
            if(!empty($session['repertoryId'])){
                $idArr = $session['repertoryId'];
                $id = implode(',', $idArr);
            }
            if(!empty($id)){
                $where[] = "repertory_id in ($id)";
                $whereStr = implode ( ' and ', $where );
                $repertory = BusRepertory::find()->where($whereStr)->orderBy('repertory_id desc')->asArray()->all();
                if(!empty($session['repertoryNum'])){
                    $incnumArr = $session['repertoryNum'];
                    foreach ($repertory as $rk => $rv){
                        foreach ($incnumArr as $ik => $iv){
                            if($rv['repertory_id'] == $iv['id']){
                                array_push($repertory[$rk],$iv['num']);
                            }
                        }
                    }
                }
                $count = BusRepertory::find()->where($whereStr)->count();
            }
            return $this->render('storage',[
                'repertory' => $repertory,
                'count' => $count
            ]);
        }
        //生成标识号
        $user = $this->userInfo;
        $uniqueNum = Util::getSerialNumber($user->uid);
        //获取数据
        $remark = $this->request->post('inc_remark');
        $repertory_id = $this->request->post('repertory_id');
        $goods_name = $this->request->post('goods_name');
        $goods_specs = $this->request->post('goods_specs');
        $repertory_count = $this->request->post('repertory_count');
        $inc_count = $this->request->post('inc_count');
        for($j=0;$j<count($inc_count);$j++){
            if(empty($inc_count[$j])){
                $this->error('请输入入库数量');
            }
        }
        $supplier_name = $this->request->post('supplier_name');
        $goods_brand = $this->request->post('goods_brand');
        $goods_series = $this->request->post('goods_series');
        $goods_category = $this->request->post('goods_category');
        //成本价和零售价
        $goods_sell_price = $this->request->post('goods_sell_price');
        $goods_cost_price = $this->request->post('goods_cost_price');
        if(Util::utf8_strlen($remark) > 200){
            $this->error('备注不超过200字！');
        }
        //保存数据并修改库存量
        //开启事务
        $transAction = \Yii::$app->db->beginTransaction();
        try {
            for($i=0;$i < count($repertory_id); $i++){
                //修改商品库存信息
                $where = $this->where;
                $where[] = 'repertory_id = :id';
                $bind[':id'] = $repertory_id[$i];
                $whereStr = implode ( ' and ', $where );
                $repertoryOne = BusRepertory::find()->where($whereStr,$bind)->one();
                //修改库存量
                $repertoryOne->repertory_count = $repertoryOne->repertory_count + $inc_count[$i];
                //老板修改商品成本价，零售价
                if($user->user_type == 3){
                    $repertoryOne->goods_cost_price = $goods_cost_price[$i];
                    $repertoryOne->goods_sell_price = $goods_sell_price[$i];
                }elseif ($user->user_type == 4){//店长
                    $repertoryOne->goods_cost_price = 0;
                }
                $repertoryOne->save(false);
                //保存商品入库信息
                $repertoryInc = new BusRepertoryInc();
                $repertoryInc->goods_specs = $goods_specs[$i];
                $repertoryInc->goods_name = $goods_name[$i];
                $repertoryInc->repertory_count = $repertoryOne->repertory_count;
                if($inc_count[$i] == ''){
                    $inc_count[$i] = 0;
                }
                $repertoryInc->inc_count = $inc_count[$i];
                $repertoryInc->supplier_name = $supplier_name[$i];
                $repertoryInc->goods_brand = $goods_brand[$i];
                $repertoryInc->goods_series = $goods_series[$i];
                $repertoryInc->goods_category = $goods_category[$i];
                if($goods_sell_price[$i] == ''){
                    $goods_sell_price[$i] = 0;
                }
                $repertoryInc->goods_sell_price = $goods_sell_price[$i];
                if($goods_cost_price[$i] == ''){
                    $goods_cost_price[$i] = 0;
                }
                $repertoryInc->goods_cost_price = $goods_cost_price[$i];
        
                $repertoryInc->inc_remark = $remark;
                $repertoryInc->inc_time = date('Y-m-d H:i:s');
                $repertoryInc->unique_flag = $uniqueNum;
                $repertoryInc->shop_id = $user->shop_id;
                $repertoryInc->boss_id = $user->boss_uid;
                $repertoryInc->save(false);
                
            }
            //清空session
            unset($session['repertoryId']);
            unset($session['barCode']);
            //提交
            $transAction->commit();
            $this->redirect(Url::toRoute(['repertory/repertorymanage']));
        
        } catch (\Exception $e) {
            //回滚
            $transAction->rollBack();
            $this->error("入库失败");
        }
        
    }
    
    
    
    /**
     * 入库流水
     * @date: 2016年2月26日 
     * @author: chenxiaolin
     */
    public function actionIncrecord(){
        $start_time = $this->request->get('start_time');
        $end_time = $this->request->get('end_time');
        $where = $this->where;
        $bind = [];
        if($start_time != ''){
            $where[] = 'inc_time >= :starttime';
			$bind[':starttime'] = $start_time.' 00:00:00';
        }
        if($end_time != ''){
            $where[] = 'inc_time <= :endtime';
			$bind[':endtime'] = $end_time.' 59:59:59';
        }
        $whereStr = implode(' and ', $where);
        $query = BusRepertoryInc::find()->where($whereStr,$bind)->groupBy('unique_flag');
        //分页
        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count(),'pageSize' => $this->pageNavLimit]);
        $list = $query->offset($pages->offset)->limit($pages->limit)->orderBy('inc_time desc')->asArray()->all(); 
        
        $i = 0;
        $data = [];
        foreach ($list as $k => $v){
            //根据标识号查询同批入库商品
            $unique_flag = $v['unique_flag'];
            $query = BusRepertoryInc::find()->where("unique_flag = $unique_flag");
            //共计数量
            $count = $query->sum('inc_count');
            //日期
            $date = $v['inc_time'];
            //入库明细
            $record = $query->asArray()->all();
            $str = [];
            foreach ($record as $k => $v){
                $str[$k] = $v['goods_name'].$v['goods_specs'].'('.$v['inc_count'].')';
                $strs = implode(',', $str);
            }
            $data[$i] = [
                'unique_flag' => $unique_flag,
                'count' => $count,
                'date' => $date,
                'record' => $str
            ];
            $i++;
        }
        
        return $this->render('increcord',[
            'data' => $data,
            'page' => $pages,
            'start_time' => $start_time,
            'end_time' => $end_time
        ]);
    }
    
    /**
     * 入库详情
     * @date: 2016年2月26日 
     * @author: chenxiaolin
     */
    public function actionIncrecorddetal(){
        $this->layout = "/alert";
        //去掉调试栏
        $this->disableDebugtool();
        $unique_flag = $this->request->get('unique_flag');
        $where = $this->where;
        $where[] = 'unique_flag = :flag';
        $bind[':flag'] = $unique_flag;
        $whereStr = implode(' and ', $where);
        
        $data = BusRepertoryInc::find()->where($whereStr,$bind)->all();
        //备注信息
        $remark = '';
        foreach ($data as $k){
            $remark = $k['inc_remark'];
        }
        return $this->render('increcorddetal',[
            'data' => $data,
            'remark' => $remark
        ]);
    }
    
    /**
     * 导出入库Excel
     * @date: 2016年2月27日
     * @author: chenxiaolin
     */
    public function actionIncexcel(){
        $userInfo = $this->userInfo;
        //创建一个excel
        $objPHPExcel = new \PHPExcel();
        //创建新的内置表
        $objPHPExcel->createSheet();
        //设置活动sheet
        $objPHPExcel->setActiveSheetIndex(0);
        //获取当前活动sheet
        $objSheet = $objPHPExcel->getActiveSheet();
        //设置title
        //老板
        if($userInfo->user_type == 3){
            $objSheet->setCellValue('A1','商品名称')->setCellValue('B1','规格')
            ->setCellValue('C1','库存')->setCellValue('D1','入库数量')->setCellValue('E1','供应商')
            ->setCellValue('F1','品牌')->setCellValue('G1','系列')->setCellValue('H1','类别')->setCellValue('I1','成本价')->setCellValue('J1','零售价');
        }
        //店长
        if($userInfo->user_type == 4){
            $objSheet->setCellValue('A1','商品名称')->setCellValue('B1','规格')
            ->setCellValue('C1','库存')->setCellValue('D1','入库数量')->setCellValue('E1','供应商')
            ->setCellValue('F1','品牌')->setCellValue('G1','系列')->setCellValue('H1','类别')->setCellValue('I1','零售价');
        }
        //获取数据
        $where = $this->where;
        $whereStr = implode(' and ', $where);
        $repertoryInc = BusRepertoryInc::find()->where($whereStr)->asArray()->all();
        $i = 2;
        foreach ($repertoryInc as $k => $v){
            //老板
            if($userInfo->user_type == 3){
                $objSheet->setCellValue('A'.$i,$v['goods_name'])->setCellValue('B'.$i,$v['goods_specs'])
                ->setCellValue('C'.$i,$v['repertory_count'])->setCellValue('D'.$i,$v['inc_count'])
                ->setCellValue('E'.$i,$v['supplier_name'])->setCellValue('F'.$i,$v['goods_brand'])
                ->setCellValue('G'.$i,$v['goods_series'])->setCellValue('H'.$i,$v['goods_category'])
                ->setCellValue('I'.$i,$v['goods_cost_price'])->setCellValue('J'.$i,$v['goods_sell_price']);
            }
            //店长
            if($userInfo->user_type == 4){
                $objSheet->setCellValue('A'.$i,$v['goods_name'])->setCellValue('B'.$i,$v['goods_specs'])
                ->setCellValue('C'.$i,$v['repertory_count'])->setCellValue('D'.$i,$v['inc_count'])
                ->setCellValue('E'.$i,$v['supplier_name'])->setCellValue('F'.$i,$v['goods_brand'])
                ->setCellValue('G'.$i,$v['goods_series'])->setCellValue('H'.$i,$v['goods_category'])
                ->setCellValue('I'.$i,$v['goods_sell_price']);
            }
            $i++;
        }
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
        Util::browser_export('Excel5','repertoryInc.xls');//输出到浏览器
        $objWriter->save("php://output");
    }
}















